#import <Cocoa/Cocoa.h>

#include "GraphicManager.hpp"
#include "MemoryManager.hpp"
#include "MacApplication.h"
#include "OpenGL/OpenGLGraphicsManager.hpp"
#import "AppDelegate.h"

using namespace My;

namespace My {
    GfxConfiguration config(8, 8, 8, 8, 32, 0, 0, 960, 540, "GameEngineFromScratch(Mac)");
    IApplication* g_pApp              = static_cast<IApplication*>(new MacApplication(config));
    GraphicManager* g_pGraphicManager = static_cast<GraphicManager*>(new OpenGLGraphicsManager());
    MemoryManager* g_pMemoryManager   = new MemoryManager();
}

int My::MacApplication::Initialize()
{
     @autoreleasepool {
        // 创建应用
        NSApplication* application = [NSApplication sharedApplication];
        // 创建代理
        AppDelegate* appDelegate = [[AppDelegate alloc] init];
        appDelegate.cfg = this->m_Config;
        // 配置应用代理
        [application setDelegate:appDelegate];
        // 配置菜单
        application.mainMenu = mainMenu();
        // 运行应用
        [application run];
    }
    return 0;
}

void My::MacApplication::Finalize()
{

}

void My::MacApplication::Tick()
{

}

// 创建菜单
NSMenu* My::MacApplication::mainMenu() 
{
    NSMenu* menu = [NSMenu new];

    // 应用和File菜单
    NSMenuItem* mainAppMainItem = [[NSMenuItem alloc] initWithTitle: @"App" action:nil keyEquivalent: @""];
    NSMenuItem* mainFileMainItem = [[NSMenuItem alloc] initWithTitle: @"File" action:nil keyEquivalent: @""];

    [menu addItem: mainAppMainItem];
    [menu addItem: mainFileMainItem];
    
    // 应用的子菜单
    NSMenu* appMenu = [NSMenu new];
    mainAppMainItem.submenu = appMenu;
    
    NSMenu* appServiceMenu = [NSMenu new];
    NSApp.servicesMenu = appServiceMenu;
    
    [appMenu addItemWithTitle:@"About" action:nil keyEquivalent:@""];
    [appMenu addItem: [NSMenuItem separatorItem]];

    [appMenu addItemWithTitle:@"Preference..." action:nil keyEquivalent:@""];
    [appMenu addItem: [NSMenuItem separatorItem]];

    [appMenu addItemWithTitle:@"Hide" action:@selector(hide:) keyEquivalent:@"h"];

    //  Hide Others
    NSMenuItem* hideOtherItem = [[NSMenuItem alloc] initWithTitle: @"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent: @"h"];
    hideOtherItem.keyEquivalentModifierMask = NSEventModifierFlagCommand + NSEventModifierFlagOption;
    [appMenu addItem: hideOtherItem];

    [appMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@"h"];
    [appMenu addItem: [NSMenuItem separatorItem]];

    [appMenu addItemWithTitle:@"Services" action:nil keyEquivalent:@"h"].submenu = appServiceMenu;
    [appMenu addItem: [NSMenuItem separatorItem]];

    [appMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@"q"];

    // File 的子菜单
    NSMenu* fileMenu = [[NSMenu alloc] initWithTitle:@"File"];
    mainFileMainItem.submenu = fileMenu;
    [fileMenu addItemWithTitle:@"New..." action:@selector(newDocument:) keyEquivalent:@"n"];

    return menu;
}

